package com.mmg.spzx.manager.interceptor;

import com.alibaba.fastjson.JSON;
import com.mmg.spzx.model.entity.system.SysUser;
import com.mmg.spzx.model.vo.common.Result;
import com.mmg.spzx.model.vo.common.ResultCodeEnum;
import com.mmg.spzx.utils.AuthContextUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

/**
 * 登录认证拦截器
 */
@Component
public class LoginAuthInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取请求方式
        String method = request.getMethod();
        //如果请求方式是OPTIONS预检请求，直接放行
        if ("OPTIONS".equalsIgnoreCase(method)) return true;
        //从请求头中获取token
        String token = request.getHeader("token");
        //token为空，返回错误提示
        if (token == null || "".equals(token.trim())) {
            responseNoLoginInfo(response);
            return false;
        }
        //token不为空，获取用户信息
        //从redis中获取用户信息
        String json = redisTemplate.opsForValue().get("user:login" + token);
        //获取用户信息失败，返回错误提示
        if (json == null || "".equals(json.trim())) {
            responseNoLoginInfo(response);
            return false;
        }
        //获取用户信息成功，把用户信息放入ThreadLocal中
        AuthContextUtil.set(JSON.parseObject(json, SysUser.class));
        //把redis中的用户信息更新过期时间，延长30分钟
        redisTemplate.expire("user:login" + token, 30, TimeUnit.MINUTES);
        return true;
    }

    //响应208状态码给前端
    private void responseNoLoginInfo(HttpServletResponse response) {
        Result<Object> result = Result.build(null, ResultCodeEnum.LOGIN_AUTH);
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(JSON.toJSONString(result));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (writer != null) writer.close();
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //将ThreadLocal中的用户信息清空
        AuthContextUtil.remove();
    }
}
